package arcane.object.gui;

import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import arcane.object.game.sprite.MenuSprite;

import com.golden.gamedev.engine.BaseInput;

public class FrameWork extends MenuSprite {
	protected BaseInput bsInput;
	private List<MenuSprite> components;

	private MenuSprite focused;
	private MenuSprite mouseOverSprite;
	private boolean mouseEntered;

	private boolean mouseOver;

	public FrameWork(BaseInput bsInput, int x, int y, int width, int height) {
		super(x, y);
		this.width = width;
		this.height = height;
		this.bsInput = bsInput;
		components = new ArrayList<MenuSprite>();
		mouseEntered = false;
	}

	public void setFocused(MenuSprite s) {
		for (int i = 0; i < components.size(); i++) {
			if (components.get(i).equals(s)) {
				if (focused != null)
					focused.setFocused(false);
				this.focused = components.get(i);
				components.get(i).setFocused(true);
			}
		}
	}

	public void update(long time) {
		int key = bsInput.getKeyPressed();
		if (key != BaseInput.NO_KEY) {
			switch (key) {

			}
		}
		int x = bsInput.getMouseX();
		int y = bsInput.getMouseY();
		if (getBounds().contains(x, y)) {
			mouseOver = true;
			boolean mousePressed = bsInput.isMousePressed(MouseEvent.BUTTON1);
			boolean firedPressed = false;
			boolean firedReleased = false;
			boolean mouseReleased = bsInput.isMouseReleased(MouseEvent.BUTTON1);
			if (mouseOverSprite != null
					&& !mouseOverSprite.getBounds().contains(x, y)) {
				mouseOverSprite.mouseExited(x, y);
				mouseOverSprite = null;
			}
			for (int i = components.size() - 1; i > -1; i--) {
				MenuSprite comp = components.get(i);
				if (comp != null && comp.getBounds().contains(x, y)) {
					if (mouseOverSprite == null) {
						mouseOverSprite = comp;
						mouseOverSprite.mouseEntered(x, y);
					}
					// Call mousePressed on component pressed on
					if (!firedPressed && mousePressed) {
						System.out.println("Fire pressed on: " + comp);
						firedPressed = true;
						if (focused != null)
							focused.setFocused(false);
						comp.mouseDown(x, y);
						comp.setFocused(true);
						focused = comp;
					}
					if (!firedReleased && mouseReleased) {
						firedReleased = true;
						comp.mouseClicked(x, y);
					}
				}
			}

		}
		for (int i = components.size() - 1; i > -1; i--) {
			components.get(i).update(time);
		}
	}

	public void add(MenuSprite c) {
		this.components.add(c);
	}
	
	public void drawBackground(Graphics2D g, int x, int y){
		g.setColor(color);
		g.fillRect((int) getScreenX(), (int) getScreenY(), width, height);
	}
	public void render(Graphics2D g, int x, int y) {
		this.drawBackground(g, x, y);
		for (int i = 0; i < components.size(); i++) {
			components.get(i).render(g);
		}
	}
}